{extend name="normal_base" /}
{block name="navigation"}{/block}
{block name="css"}
<style>
    .layui-form-item{
        margin: 2px;
    }

    .layui-form input.layui-input{
        width: 200px;
    }

    .status-show{
        color: #FF5722;
    }

    .can-click:hover{
        cursor:pointer;
        color: #48AFFC;
    }
</style>
{/block}
{block name="body"}
<div class="x-body">
    <blockquote class="layui-elem-quote" style="color: #AAAAAA">Tip ： 双击表格中的行、单击合同编号 均可查看合同详细信息；点击客户单位名称或客户编号可查看客户详情</blockquote>

    <form class="layui-form" action="" lay-filter="form-id"  method="get" id="search-form-id">
        <div class="layui-row">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">合同年度：</label>
                    <div class="layui-input-inline">
                        <input class="layui-input" placeholder="" name="year" id="year" value="{$year}">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">合同编号：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="contract_number" id="contract_number"  placeholder="" value="{$contract_number}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">客户名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="customer_name" id="customer_name"  placeholder="" value="{$customer_name}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">项目名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="project_name" id="project_name"  placeholder="" value="{$project_name}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">营销经理：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="sale_manager" id="sale_manager"  placeholder="" value="{$sale_manager}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">签订公司：</label>
                    <div class="layui-input-inline">
                        <select name="sign_company_code" id="sign_company_code" lay-filter="sign_company_code">
                            <option value=''>请选择</option>
                            {foreach name='sign_company_list' item='vo'}
                            <option value="{$vo.code}" {if condition="$vo.code==$sign_company_code"}selected="selected"{/if}>{$vo.sign_company}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">金额最小：</label>
                    <div class="layui-input-inline" style="width: 100px;">
                        <input type="text" name="contract_amount_min" id="contract_amount_min" placeholder="￥" value="{$contract_amount_min}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">金额最大：</label>
                    <div class="layui-input-inline" style="width: 100px;">
                        <input type="text" name="contract_amount_max" id="contract_amount_max" placeholder="￥" value="{$contract_amount_max}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">负责人：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="project_manager" id="project_manager"  placeholder="" value="{$project_manager}" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">客户星级：</label>
                    <div class="layui-input-inline">
                        <select name="star_level" id="star_level" lay-filter="star_level">
                            <option value=0>请选择</option>
                            {foreach name="star_level_config_info" item="vo"}
                            <option value={$vo} {if condition="$vo==$star_level"} selected="selected" {/if}>{$vo}星</option>
                            {/foreach}
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">合同状态：</label>
                    <div class="layui-input-inline">
                        <select name="status" id="status" lay-filter="status">
                            <option value=0>发出</option>
                            <option value=1 {if condition="1==$status"}selected="selected"{/if}>未收回</option>
                            <option value=2 {if condition="2==$status"}selected="selected"{/if}>已收回</option>
                            <option value=3 {if condition="3==$status"}selected="selected"{/if}>废弃</option>
                        </select>
                    </div>
                </div>

                <!--项目分组-->
                <div class="layui-form-item">
                    <label class="layui-form-label">项目组：</label>
                    <div class="layui-input-inline">
                        <select name="project_group_id" id="project_group_id" lay-filter="sign_company_code">
                            <option value=''>请选择</option>
                            {foreach name='project_group_list' item='v' key="k"}
                            <option value="{$k}" {if condition="$k==$project_group_id"}selected="selected"{/if}>{$v}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">客户区域：</label>
                    <div class="layui-input-inline">
                        <select name="province_id" lay-filter="region" id="province">
                            <option value=0>指定省</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-inline">
                        <select name="city_id" lay-filter="region" id="city">
                            <option value=0>指定市</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-inline">
                        <select name="district_id" lay-filter="region" id="district">
                            <option value=0>指定县/区</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">业务类型：</label>
                    <div class="layui-input-inline">
                        <select name="class" id="class" lay-filter="class">
                            <option value=0>指定大类</option>
                            <option value=></option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">业务类型：</label>
                    <div class="layui-input-inline">
                        <select name="type" id="type" lay-filter="type">
                            <option value=0>指定小类</option>
                            <option value=></option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-progress" lay-showPercent="true" lay-filter="down-progress" id="down-progress-bar" style="display: none;">
            <div class="layui-progress-bar" lay-percent="0%" id="down-progress-bar-per"></div>
        </div>
    </form>

    <div style="clear:both"></div>
    <xblock>
        <button class="layui-btn"  lay-submit="" lay-filter="sreach" id="sreach-by-where">搜索</button>
        <button type="reset" class="layui-btn layui-btn-normal" id="reset-search">重置</button>
        <button class="layui-btn" onclick="javascript:location.replace(location.href);">刷新</button>
        <button class="layui-btn layui-btn-normal" onclick="x_admin_show('添加合同','{:url(\'add\')}')">添加</button>
        <button class="layui-btn" id="export-contract-id">导出</button>
        <button class="layui-btn layui-btn-danger" onclick="delAll()">批量删除</button>
        <span class="x-right" style="line-height:40px">共有数据：{$contract_list->toArray()['total']} 条</span>
    </xblock>

    <table class="layui-table" lay-size="">
        <thead>
        <tr>
            <th>
                <div class="layui-unselect header layui-form-checkbox" lay-skin="primary"><i class="layui-icon">&#xe605;</i></div>
            </th>
            <th>合同编号</th>
            <th>合同状态</th>
            <th>客户单位名称</th>
            <th>客户编号</th>
            <th>项目组</th>
            <th>营销经理</th>
            <th>项目名称</th>
            <th>项目负责人</th>
            <th>合同金额（元）</th>
            <!--<th>是否含税</th>-->
            <!--<th>录入时间</th>-->
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {foreach name="contract_list" item="vo"}
        <tr class="customer-tr" data-id='{$vo.id}' customer-id="{$vo.customer_id}">
            <td>
                <div class="layui-unselect layui-form-checkbox" lay-skin="primary" data-id='{$vo.id}'><i class="layui-icon">&#xe605;</i></div>
            </td>
            <td class="can-click show-contract">{$vo.contract_number}</td>
            <td class="status-show">{if condition="isset($status_desc[$vo['status']])"}{$status_desc[$vo['status']]}{/if}</td>
            <td class="can-click show-customer">{$vo.company_name}</td>
            <td class="can-click show-customer">{$vo.customer_number}</td>
            <td>{if condition="isset($project_group_list[$vo.project_group_id])"}{$project_group_list[$vo.project_group_id]}{/if}</td>
            <td>{$vo.sale_manager}</td>
            <td>{$vo.project_name}</td>
            <td>{$vo.project_manager}</td>
            <td>{$vo.contract_amount}</td>
            <!--<td>{$vo.is_include_tax ? '是' : '否'}</td>-->
            <!--<td>{$vo.create_time}</td>-->
            <!--<td>{$vo.create_time}</td>-->
            <td class="td-manage">

                <!--初始状态的合同才能被回收-->
                {if condition="$vo.status == CONTRACT_STATUS_INIT"}
                <a title="回收"  onclick="x_admin_show('回收合同','recycle?id={$vo.id}&number={$vo.contract_number}', 550, 480)" href="javascript:;">
                    <i class="fa fa-recycle"></i>
                </a>
                {/if}

                {if condition="$vo.status != CONTRACT_STATUS_DISCARD"}
                <a title="作废" onclick="discard_contract(this, {$vo.id}, '{$vo.contract_number}')" href="javascript:;">
                    <i class="layui-icon">&#xe639;</i>
                </a>
                <a title="编辑"  onclick="x_admin_show('编辑合同','edit/id/{$vo.id}')" href="javascript:;">
                    <i class="layui-icon">&#xe642;</i>
                </a>
                {/if}

                {if condition="$vo.status == CONTRACT_STATUS_RECYCLE && $vo.scanning_file"}
                <a title="下载扫描件" onclick="download_scanning_file(this, '{$vo.scanning_file}')" href="javascript:;">
                    <i class="fa fa-download"></i>
                </a>
                {/if}

                <a title="删除" onclick="delOne(this,{$vo.id})" href="javascript:;">
                    <i class="layui-icon">&#xe640;</i>
                </a>
            </td>
        </tr>
        {/foreach}
        </tbody>
    </table>
    <!--分页-->
    {$contract_list->render()}
</div>

{/block}

{block name="script"}
<script src="__JS__/jquery.fileDownload.js"></script>
<script>
    layui.use(['laydate', 'form','layer', 'element'], function(){
        var laydate = layui.laydate;
        var element = layui.element;

        $ = layui.jquery;
        var form = layui.form
                ,layer = layui.layer;

        //执行一个laydate实例
        laydate.render({
            elem: '#start' //指定元素
        });

        //执行一个laydate实例
        laydate.render({
            elem: '#end' //指定元素
        });

        //执行一个laydate实例- 年度选择
        laydate.render({
            elem: '#year' //指定元素
            ,type: 'year'
            /*//,range: true //范围选择
            ,format: 'yyyy' //格式显示
            ,theme: 'default' //主题：default（默认简约）、molv（墨绿背景）、#颜色值（自定义颜色背景）、grid（格子主题）*/
        });

        //初始化省级信息
        $.ajax({
            type: "post",
            url: "{:url('admin/region/get_region_by_parent_id', 'pid=1')}",
            dataType: "json",
            success: function(data){
                if (data.code == 1) {
                    layer.msg('获取地区清单错误，建议尝试刷新页面！',{icon:5,time:1500});
                } else {
                    var province_list = data.data;

                    var province_id = {$province_id};
                    var city_id = {$city_id};
                    var district_id = {$district_id};
                    $("#province").empty();
                    $("#province").append("<option value='0'>指定省</option>");
                    for (var i=0; i < province_list.length; i++) {
                        $("#province").append("<option value="+province_list[i]['region_id']+">"+province_list[i]['region_name']+"</option>");
                    }
                    $("#province").val(province_id);
                    form.render('select', 'form-id');

                    //加载市
                    if (province_id > 0) {
                        $.ajax({
                            type: "post",
                            url: "{:url('admin/region/get_region_by_parent_id')}" + '?pid='+province_id,
                            dataType: "json",
                            success: function(data){
                                if (data.code == 1) {
                                    layer.msg(data.msg,{icon:5,time:1500});
                                } else {
                                    var region_list = data.data;
                                    $("#city").empty();
                                    $("#city").append("<option value='0'>指定市</option>");
                                    for (var i=0; i < region_list.length; i++) {
                                        $("#city").append("<option value="+region_list[i]['region_id']+">"+region_list[i]['region_name']+"</option>");
                                    }
                                    $("#city").val(city_id);
                                    form.render('select', 'form-id');
                                }
                            }, error: function(){
                                layer.msg("请求地区清单出错",{icon:5,time:1500});
                            }
                        });
                    }

                    //加载县区
                    if (city_id > 0) {
                        $.ajax({
                            type: "post",
                            url: "{:url('admin/region/get_region_by_parent_id')}" + '?pid=' + city_id,
                            dataType: "json",
                            success: function (data) {
                                if (data.code == 1) {
                                    layer.msg(data.msg, {icon: 5, time: 1500});
                                } else {
                                    var region_list = data.data;
                                    $("#district").empty();
                                    $("#district").append("<option value='0'>指定区/县</option>");
                                    for (var i = 0; i < region_list.length; i++) {
                                        $("#district").append("<option value=" + region_list[i]['region_id'] + ">" + region_list[i]['region_name'] + "</option>");
                                    }
                                    $("#district").val(district_id);
                                    form.render('select', 'form-id');
                                }
                            }, error: function () {
                                layer.msg("请求地区清单出错", {icon: 5, time: 1500});
                            }
                        });
                    }
                }
            }, error: function(){
                layer.msg("请求地区清单出错",{icon:5,time:1500});
            }
        });

        //监听省市区下拉框选择
        form.on('select(region)', function(data){
            var pid = data.value;   //当前选中的地区id：region_id
            var type = $(data.elem).attr('id');
            if (pid > 0 && type != 'district') {

                var id = '';
                var name = '';
                if (type == 'province') {
                    id = 'city';
                    name = '市';
                } else if (type == 'city') {
                    id = 'district';
                    name = '县/区';
                } else {
                    layer.msg('省市区信息异常！',{icon:5,time:1500});
                    return;
                }

                $.ajax({
                    type: "post",
                    url: "{:url('admin/region/get_region_by_parent_id')}" + '?pid='+pid,
                    dataType: "json",
                    success: function(data){
                        if (data.code == 1) {
                            layer.msg(data.msg,{icon:5,time:1500});
                        } else {
                            var region_list = data.data;
                            $("#"+id).empty();
                            $("#"+id).append("<option value='0'>指定"+name+"</option>");
                            for (var i=0; i < region_list.length; i++) {
                                $("#"+id).append("<option value="+region_list[i]['region_id']+">"+region_list[i]['region_name']+"</option>");
                            }
                            form.render('select', 'form-id');
                        }
                    }, error: function(){
                        layer.msg("请求地区清单出错",{icon:5,time:1500});
                    }
                });
            }
        });

        /*重置按钮*/
        $('#reset-search').bind('click', function () {
            $('#year').val('');
            $('#contract_number').val('');
            $('#customer_name').val('');
            $('#project_name').val('');
            $('#sale_manager').val('');
            $('#project_manager').val('');
            $('#am').val('');
            $('#province').val(0);
            $('#city').val(0);
            $('#district').val(0);
            $('#star_level').val(0);
            $('#project_group_id').val(0);
            $('#sign_company_code').val('');
            init_contract_type(0);
            form.render('select');
        });

        /*初始化业务类型*/
        init_contract_type({$class}, {$type});

        /*模仿：xcity.js实现*/
        function init_contract_type(class_id, type_id) {
            var contract_type_list = {$contract_type_arr};
            var contract_class = $('#class');
            var contract_type = $('#type');
            var type_list = [];

            showClass(class_id);
            showType(type_list);

            function showClass(class_id) {
                var flag = false;
                contract_class.empty();
                contract_class.append("<option value='0'>请选择类型</option>")
                for (var i in contract_type_list) {
                    if (class_id > 0 && class_id == contract_type_list[i]['id']) {
                        //传入的大类型id能被找到，那么子类型的id需要被指定
                        flag = true;
                        type_list = contract_type_list[i]['son_list'];
                        contract_class.append("<option value='"+contract_type_list[i]['id']+"' selected='selected'>"+contract_type_list[i]['type']+"</option>")
                    } else {
                        contract_class.append("<option value='"+contract_type_list[i]['id']+"'>"+contract_type_list[i]['type']+"</option>")
                    }
                }

                if (!flag) {
                    type_list = [];
                }
            }

            function showType(type_list) {
                contract_type.empty();
                contract_type.append("<option value='0'>请选择子类型</option>")

                for (var i in type_list) {
                    if (type_list[i]['id'] == type_id) {
                        contract_type.append("<option value='"+type_list[i]['id']+"' selected='selected'>"+type_list[i]['type']+"</option>");
                    } else {
                        contract_type.append("<option value='"+type_list[i]['id']+"'>"+type_list[i]['type']+"</option>");
                    }

                }
            }

            form.render('select');

            /*监听大类型的改变*/
            form.on('select(class)', function(data){
                class_id = data.value;
                showClass(class_id);
                contract_class.val(class_id);
                showType(type_list);
                form.render('select');
            });
        }

        /*导出合同列表*/
        $('#export-contract-id').bind('click', function () {
            layer.confirm("您确定要导出当前条件下（最近一次搜索）的：{$contract_list->toArray()['total']} 条数据吗？", function (index) {
                //Yes
                layer.close(index);
                //获取下载条件:
                /*年度*/
                var year = $('#year').val();
                /*合同编号*/
                var contract_number = $('#contract_number').val();
                /*客户名称*/
                var customer_name = $('#customer_name').val();
                /*项目名称*/
                var project_name = $('#project_name').val();
                /*营销经理*/
                var sale_manager = $('#sale_manager').val();
                /*签订公司*/
                var sign_company_code = $('#sign_company_code').val();
                /*金额*/
                var contract_amount_min = $('#contract_amount_min').val();
                /*合同编号*/
                var contract_amount_max = $('#contract_amount_max').val();
                /*负责人*/
                var project_manager = $('#project_manager').val();
                /*客户星级*/
                var star_level = $('#star_level').val();
                /*合同状态*/
                var status = $('#status').val();
                /*项目组id*/
                var project_group_id = $('#project_group_id').val();
                /*客户区域*/
                var province_id = $('#province').val();
                var city_id = $('#city').val();
                var district_id = $('#district').val();
                /*业务类型*/
                var c_class = $('#class').val();
                var c_type = $('#type').val();

                var url = "{:url('admin/Contract/export_contracts')}" + '?year=' + year + '&contract_number='+contract_number + '&customer_name=' + customer_name + '&project_name='+project_name + '&sale_manager='+sale_manager + '&sign_company_code='+sign_company_code + '&contract_amount_min='+contract_amount_min + '&contract_amount_max='+contract_amount_max + '&project_manager='+project_manager + '&star_level='+star_level + '&status='+status + '&project_group_id='+project_group_id + '&province_id='+province_id + '&city_id='+city_id + '&district_id='+district_id + '&class='+c_class + '&type='+c_type;

                var inter;
                var percent = 0;
                var random = 0;

                /*异步下载*/
                $.fileDownload(url,{
                    httpMethod: 'GET',
                    //data:,
                    prepareCallback:function(url){
                        $('#down-progress-bar').show();

                        inter = setInterval(function () {
                            //clearInterval(interva); 清除定时器
                            if (percent < 90) {
                                //从任意值开始 至 任意值:parseInt(Math.random()*(上限-下限+1)+下限)
                                random = parseInt(Math.random() * (6 - 3 + 1) + 3);
                                percent += random;
                                element.progress('down-progress', percent + '%');
                            }
                        }, 200);
                    },
                    successCallback:function(url){
                        clearInterval(inter);
                        element.progress('down-progress', 100 + '%');
                        setTimeout(function () {
                            $('#down-progress-bar').hide();
                        }, 3200);
                    },
                    failCallback: function (html, url) {
                        layer.msg(html,{icon:5,time:1500});
                        $('#down-progress-bar').hide();
                    }
                });
            }, function (index) {
                //Cancel
                layer.close(index);
            });
        });
    });

    /*按钮绑定提交表单*/
    $('#sreach-by-where').bind('click', function () {
        $("#search-form-id").submit();
    });

    /*双击查看详情*/
    $('.customer-tr').dblclick(function () {
        x_admin_show('合同详情','info/id/' + $(this).attr('data-id'));
    });

    /*点击查看合同信息*/
    $('.show-contract').bind('click', function () {
        x_admin_show('合同详情','info/id/' + $(this).parent().attr('data-id'));
    });

    /*点击查看客户信息*/
    $('.show-customer').bind('click', function () {
        x_admin_show('客户详情','{:url("customer/info")}' + '?id=' +$(this).parent().attr('customer-id'));
    });

    function discard_contract(obj, id, contract_number) {
        var layer = layui.layer;
        layer.confirm('合同一经作废后，不能再恢复，确定要作废吗？', function(index){
            layer.closeAll();
            x_admin_show('作废合同','discard?id='+id+'&number='+contract_number, 500, 350);
        });
    }

    /*下载扫描件*/
    function download_scanning_file(obj, file_url) {
        var url = '{:url("down_scnning_file")}';
        var layer = layui.layer;
        $.fileDownload(url,{
            httpMethod: 'GET',
            data:{file_url:file_url},
            prepareCallback:function(url){
                //layer.load();
            },
            successCallback:function(url){
                /*layer.closeAll('loading');
                layer.msg('下载成功', {icon:6, time:1500});*/
            },
            failCallback: function (html, url) {
                //layer.closeAll('loading');
                layer.msg(html, {icon:5, time:1500});
            }
        });
    }

    /*合同-删除*/
    function delOne(obj,id){
        layer.confirm('确认要删除吗？',function(index){
            //发异步删除数据
            $.ajax({
                type: "post",
                url: "delete?ids="+id,
                dataType: "json",
                success: function(data){
                    if (data.code == 1) {
                        layer.msg(data.msg);
                    } else {
                        layer.msg('已删除!',{icon:1,time:1000});
                        $(obj).parents("tr").remove();
                    }
                }, error: function(){
                    layer.msg("请求出错",{icon:5,time:1000});
                }
            });
        });
    }
    /*合同-删除*/
    function delAll (argument) {
        //获取选中的id
        var data = tableCheck.getData();
        if (data.length > 0) {
            layer.confirm('确认要删除吗？',function(index){
                var success = 0;
                //捉到所有被选中的，发异步进行删除
                $.ajax({
                    type: "post",
                    url: "delete?ids="+data.join(','),
                    dataType: "json",
                    success: function(data){
                        if (data.code == 1) {
                            layer.msg(data.msg,{icon:5,time:1500});
                        } else {
                            layer.msg('已删除!',{icon:1,time:1000});
                            success = 1
                        }
                    }, error: function(){
                        layer.msg("请求出错",{icon:5,time:1000});
                    }
                });

                setTimeout(function () {
                    location.replace(location.href);
                }, 1500);
            });
        } else {
            layer.msg("您还未勾选要删除的数据",{icon:5,time:1500});
        }
    }
</script>
{/block}